package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.promote.bo.AdUpdateBO;
import com.cskaoyan.model.promote.bo.CouponCreateBO;
import com.cskaoyan.model.promote.bo.TopicUpdateBO;
import com.cskaoyan.model.promote.vo.*;
import com.cskaoyan.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class PromoteServiceImpl implements PromoteService{

    @Autowired
    AdMapper adMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    TopicMapper topicMapper;

    @Autowired
    GrouponMapper grouponMapper;

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    Oupon_userMapper ouponUserMapper;

    Groupon_rulesMapper rulesMapper;
    @Autowired
    PromoteServiceImpl(Groupon_rulesMapper rulesMapper){
        this.rulesMapper = rulesMapper;
    }

    @Override
    public BaseListData queryAds(Integer page, Integer limit, String sort, String order, String content,String name) {
        PageHelper.startPage(page, limit);
        AdExample adExample = new AdExample();
        adExample.setOrderByClause(sort + " " + order);
        if(Objects.equals(content, null)){
            content = "";
        }
        if(Objects.equals(name, null)){
            name = "";
        }
        adExample.createCriteria().andNameLike("%"+ name +"%").andContentLike("%"+ content +"%");
        List<Ad> ads = adMapper.selectByExample(adExample);

        //total不是users的size，而是满足条件（不包括）的全部的数据量
        PageInfo<Ad> pageInfo = new PageInfo<Ad>(ads);
        long total = pageInfo.getTotal();
        return BaseListData.ok(ads, total);

    }

    @Override
    public void updateAds(AdUpdateBO adUpdateBO) {
        Ad ad = new Ad();
        ad.setId(adUpdateBO.getId());
        ad.setName(adUpdateBO.getName());
        ad.setLink(adUpdateBO.getLink());
        ad.setUrl(adUpdateBO.getUrl());
        ad.setPosition(adUpdateBO.getPosition());
        ad.setContent(adUpdateBO.getContent());
        ad.setEnabled(adUpdateBO.getEnabled());
        ad.setAddTime(adUpdateBO.getAddTime());
        ad.setUpdateTime(adUpdateBO.getUpdateTime());
        ad.setDeleted(adUpdateBO.getDeleted());
        adMapper.updateByPrimaryKeySelective(ad);
    }

    @Override
    public AdCreateVO createAds(Ad ad) {
        ad.setAddTime(new Date());
        ad.setUpdateTime(new Date());
        adMapper.insertSelective(ad);
        return new AdCreateVO(ad.getId(),
                ad.getName(),
                ad.getUrl(),
                ad.getPosition(),
                ad.getContent(),
                ad.getEnabled(),
                ad.getAddTime(),
                ad.getUpdateTime());
    }

    @Override
    public void deleteAds(AdUpdateBO ad) {
        adMapper.deleteByPrimaryKey(ad.getId());
    }

    @Override
    public BaseListData queryCoupons(Integer page, Integer limit, String sort, String order, String name, Short type, Short status) {
        PageHelper.startPage(page, limit);
        CouponExample couponExample = new CouponExample();
        couponExample.setOrderByClause(sort + " " + order);
        CouponExample.Criteria criteria = couponExample.createCriteria();
        if(name != null){
            criteria.andNameLike("%"+ name +"%");
        }
        if(type != null){
            criteria.andTypeEqualTo(type);
        }
        if(status != null){
            criteria.andStatusEqualTo(status);
        }

        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        PageInfo<Coupon> pageInfo = new PageInfo<>(coupons);
        long total = pageInfo.getTotal();
        return BaseListData.ok(coupons, total);
    }

    @Override
    public void deleteCoupon(Map map) {
        couponMapper.deleteByPrimaryKey((Integer)map.get("id"));
    }

    @Override
    public CouponCreateVO createCoupon(CouponCreateBO createBO) {
        Coupon coupon = new Coupon();
        coupon.setName(createBO.getName());
        coupon.setDesc(createBO.getDesc());
        coupon.setTag(createBO.getTag());
        coupon.setTotal(coupon.getTotal());
        coupon.setDiscount(new BigDecimal(createBO.getDiscount()));
        coupon.setMin(new BigDecimal(createBO.getMin()));
        coupon.setLimit(new Short(createBO.getLimit()));
        coupon.setType(coupon.getType());
        coupon.setStatus(createBO.getStatus());
        coupon.setGoodsType(createBO.getGoodsType());
        coupon.setGoodsValue(createBO.getGoodsValue().toString());
        coupon.setTimeType(createBO.getTimeType());
        coupon.setDays(new Short(createBO.getDays()));
        coupon.setAddTime(new Date());
        coupon.setUpdateTime(new Date());
        coupon.setStartTime(createBO.getStartTime());
        coupon.setEndTime(createBO.getEndTime());
        couponMapper.insertSelective(coupon);

        return new CouponCreateVO(
                coupon.getId(),
                coupon.getName(),
                coupon.getTotal(),
                coupon.getDiscount(),
                coupon.getMin(),
                coupon.getLimit(),
                coupon.getType(),
                coupon.getStatus(),
                coupon.getGoodsType(),
                Arrays.asList(coupon.getGoodsValue()),
                coupon.getTimeType(),
                coupon.getDays(),
                coupon.getAddTime(),
                coupon.getUpdateTime());
    }

    @Override
    public CouponUpdateVO updateCoupon(Coupon coupon) {
        coupon.setUpdateTime(new Date());
        couponMapper.updateByPrimaryKeySelective(coupon);

        return new CouponUpdateVO(coupon.getId(),
                coupon.getName(),
                coupon.getDesc(),
                coupon.getTag(),
                coupon.getTotal(),
                coupon.getDiscount(),
                coupon.getMin(),
                coupon.getLimit(),
                coupon.getType(),
                coupon.getStatus(),
                coupon.getGoodsType(),
                coupon.getTimeType(),
                coupon.getDays(),
                coupon.getStartTime(),
                coupon.getEndTime(),
                coupon.getAddTime(),
                coupon.getUpdateTime(),
                coupon.getDeleted(),
                new ArrayList<>());


    }

    @Override
    public Map queryCoupon(Integer id) {
        Coupon coupon = couponMapper.selectByPrimaryKey(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",coupon.getId());
        map.put("name",coupon.getName());
        map.put("desc",coupon.getDesc());
        map.put("tag",coupon.getTag());
        map.put("total",coupon.getTotal());
        map.put("min",coupon.getMin());
        map.put("limit",coupon.getLimit());
        map.put("type",coupon.getType());
        map.put("status",coupon.getStatus());
        map.put("goodsType",coupon.getGoodsValue());
        map.put("goodsValue",coupon.getGoodsValue());
        map.put("timeType",coupon.getTimeType());
        map.put("days",coupon.getDays());
        map.put("addTime",coupon.getAddTime());
        map.put("updateTime",coupon.getUpdateTime());
        map.put("deleted",coupon.getDeleted());

        return map;
    }

    @Override
    public BaseListData queryCouponUsers(Map map) {
        String page = (String) map.get("page");
        String limit = (String) map.get("limit");
        String sort = (String) map.get("sort");
        String order = (String) map.get("order");
        String couponId = (String) map.get("couponId");
        String status = (String) map.get("status");
        String userId = (String) map.get("userId");
        // 开启分页
        PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(limit));

        Oupon_userExample ouponUserExample = new Oupon_userExample();
        ouponUserExample.setOrderByClause(sort + " " + order);
        Oupon_userExample.Criteria criteria = ouponUserExample.createCriteria();

        if(!StringUtils.isEmpty(couponId) && StringUtils.isNumeric(couponId)){
            criteria.andCouponIdEqualTo(Integer.parseInt(couponId));
        }
        if(!StringUtils.isEmpty(status) && StringUtils.isNumeric(couponId)){
            criteria.andStatusEqualTo(new Short(status));
        }
        if(!StringUtils.isEmpty(userId) && StringUtils.isNumeric(couponId)){
            criteria.andUserIdEqualTo(Integer.valueOf(userId));
        }

        List<Oupon_user> coupons = ouponUserMapper.selectByExample(ouponUserExample);

        long total = new PageInfo<>(coupons).getTotal();
        return BaseListData.ok(coupons, total);
    }

    @Override
    public BaseListData queryTopics(Integer page, Integer limit, String sort, String order, String title, String subtitle) {
        PageHelper.startPage(page,limit);
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(sort + " " + order);
        TopicExample.Criteria criteria = topicExample.createCriteria();
        if(title != null){
            criteria.andTitleLike("%"+ title+"%");
        }
        if(subtitle != null){
            criteria.andSubtitleLike("%"+ subtitle+"%");
        }

        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        long total = new PageInfo<>(topics).getTotal();

        return BaseListData.ok(topics, total);
    }

    @Override
    public TopicUpdateBO updateTopics(TopicUpdateBO updateBo) {
        Topic topic = new Topic();
        topic.setId(updateBo.getId());
        topic.setTitle(updateBo.getTitle());
        topic.setSubtitle(updateBo.getSubtitle());
        topic.setPrice(updateBo.getPrice());
        topic.setReadCount(updateBo.getReadCount());
        topic.setGoods(updateBo.getGoods().toString());
        topic.setAddTime(updateBo.getAddTime());
        topic.setContent(updateBo.getContent());
        topic.setUpdateTime(new Date());
        topicMapper.updateByPrimaryKeySelective(topic);
        updateBo.setUpdateTime(topic.getUpdateTime());
        return updateBo;
    }

    @Override
    public TopicUpdateBO createTopics(Map map) {
        Topic topic = new Topic();
        topic.setTitle((String) map.get("title"));
        topic.setSubtitle((String) map.get("subtitle"));
        topic.setContent((String) map.get("content"));
        topic.setPrice(new BigDecimal((String)map.get("price")));
        topic.setReadCount((String) map.get("readCount"));
        topic.setGoods(map.get("goods").toString());
        topic.setAddTime(new Date());
        topic.setUpdateTime(new Date());
        topicMapper.insertSelective(topic);
        return new TopicUpdateBO(topic.getId(),
                topic.getTitle(),
                topic.getSubtitle(),
                topic.getPrice(),
                topic.getReadCount(),
                topic.getGoods(),
                topic.getAddTime(),
                topic.getUpdateTime(),
                topic.getContent());
    }

    @Override
    public void deleteTopics(Map map) {
        Integer id = (Integer) map.get("id");
        if(id == null){
            return;
        }
        topicMapper.deleteByPrimaryKey(id);
    }

    @Override
    public BaseListData queryGroupOnRules(Integer page, Integer limit, String sort, String order, Integer goodsId) {
        // 开启分页
        PageHelper.startPage(page,limit);
        // 排序
        Groupon_rulesExample rulesExample = new Groupon_rulesExample();
        rulesExample.setOrderByClause(sort + " " + order);
        if(goodsId != null){
            rulesExample.createCriteria().andGoodsIdEqualTo(goodsId);
        }
        List<Groupon_rules> rules = rulesMapper.selectByExample(rulesExample);
        long total = new PageInfo<>(rules).getTotal();

        return BaseListData.ok(rules,total);
    }

    @Override
    public void deleteGroupOnRules(Map map) {
        Integer id = (Integer) map.get("id");
        if(id == null){
            return;
        }
        rulesMapper.deleteByPrimaryKey(id);
    }

    @Override
    public GroupOnCreateVO createGroupOnRules(String goodsId, String discount, String discountMember, Date expireTime){
        Groupon_rules rules = new Groupon_rules();
        Date time = new Date();
        rules.setUpdateTime(time);
        rules.setAddTime(time);
        rules.setGoodsId(Integer.valueOf(goodsId));
        rules.setDiscount(new BigDecimal(discount));
        rules.setDiscountMember(Integer.valueOf(discountMember));
        rules.setExpireTime(expireTime);
        Goods goods = goodsMapper.selectByPrimaryKey(Integer.valueOf(goodsId));
        if(goods == null){
            return null;
        }
        rules.setPicUrl(goods.getPicUrl());
        rules.setGoodsName(goods.getName());
        if(time.after(expireTime)){
            rules.setDeleted(false);
        }else {
            rules.setDeleted(true);
        }
        rulesMapper.insertSelective(rules);
        return new GroupOnCreateVO(rules.getId(),
                rules.getGoodsId(),
                rules.getGoodsName(),
                rules.getPicUrl(),
                rules.getDiscount(),
                rules.getDiscountMember(),
                rules.getAddTime(),
                rules.getUpdateTime(),
                rules.getExpireTime());

    }

    @Override
    public int updateGroupOnRules(Groupon_rules rules) {
        int i = rulesMapper.updateByPrimaryKeySelective(rules);
        return i;
    }


    @Override
    public BaseListData queryGroupOns(Integer page, Integer limit, String sort, String order, Integer goodsId) {
        PageHelper.startPage(page,limit);

        List<GroupOnInfosVO> infosVOS = grouponMapper.selectGroupOnsLeft(sort + " " + order);
        long total = new PageInfo<>(infosVOS).getTotal();

        return BaseListData.ok(infosVOS,total);
    }
}
